package com.backend.system.service.processors.user;

import cn.dev33.satoken.stp.StpUtil;
import com.backend.system.beans.user.UserLoginReq;
import com.backend.system.beans.user.UserLoginVO;
import com.backend.system.beans.user.UserRoleVO;
import com.backend.system.common.CustomException;
import com.backend.system.common.annotation.ProcessorBean;
import com.backend.system.common.enums.ActionTypeEnum;
import com.backend.system.common.enums.ErrorEnum;
import com.backend.system.common.processor.AbstractProcessorTemplate;
import com.backend.system.common.processor.ProcessorContext;
import com.backend.system.dao.entity.Role;
import com.backend.system.dao.entity.User;
import com.backend.system.util.CipherUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 用户登录处理
 *
 * @author backend-manage
 */
@Slf4j
@Component
@ProcessorBean(action = ActionTypeEnum.USER_LOGIN)
public class UserLoginProcessor extends AbstractProcessorTemplate<UserLoginReq, UserLoginVO> {

    private User user;
    private UserLoginVO userLoginVo;

    @Override
    protected void init(ProcessorContext<UserLoginReq> context) {
        user = null;
        userLoginVo = null;
    }

    @Override
    public UserLoginVO handle(ProcessorContext<UserLoginReq> context) {
        UserLoginReq req = context.getData();

        // 密码加密
        String password = req.getPassword();
        String passwordEncrypt = CipherUtil.aesPasswordEncrypt(password);
        // 获取当前要登录的账号
        String loginAccount = req.getLoginAccount();

        // 通过账号+密码查寻用户
        user = userService.searchUserByLoginInfo(loginAccount, passwordEncrypt);
        if (Objects.isNull(user)) {
            throw new CustomException(ErrorEnum.ACCOUNT_OR_PASSWORD_ERROR);
        }

        // 通过校验，登录成功
        StpUtil.login(user.getId());
        // 设置当前用户token信息
        String tokenValue = StpUtil.getTokenValueByLoginId(user.getId());

        // 组装响应
        userLoginVo = new UserLoginVO();
        userLoginVo.setToken(tokenValue);
        userLoginVo.setLoginAccount(user.getLoginAccount());
        userLoginVo.setUsername(user.getUsername());
        return userLoginVo;
    }


    @Override
    protected void after(ProcessorContext<UserLoginReq> context, UserLoginVO result) {
        // 查询当前用户的所有角色
        List<Role> roles = roleService.getRolesByUserId(user.getId());

        List<UserRoleVO> rolesVo = new ArrayList<>();
        for (Role role : roles) {
            UserRoleVO vo = new UserRoleVO();
            vo.setRoleCode(role.getCode());
            vo.setRoleName(role.getRoleName());
            vo.setRoleId(role.getId());
            rolesVo.add(vo);
        }

        // 为用户设置角色信息
        userLoginVo.setRoles(rolesVo);
    }
}
